package com.zhaungjie.base.utils.ExcelUtil.spi.impl.easy;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.zhaungjie.base.utils.ExcelUtil.ExcelUtil;
import com.zhaungjie.base.utils.ExcelUtil.spi.ExcelUtilReadHandler;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * excel-util读取处理程序
 *
 * @author zhuangjie
 * @date 2024/06/02
 */
public class ExcelUtilReadHandlerForEasy extends ExcelUtilReadHandler {
    private final ExcelReader excelReader;

    private static class ReadListenerImpl<T> implements ReadListener<T> {
        private final List<T> dataList = new ArrayList<>();
        private final ExcelUtil.ExcelReadEventListener<T> excelReadEventListener;

        public ReadListenerImpl(ExcelUtil.ExcelReadEventListener<T> excelReadEventListener) {
            this.excelReadEventListener = excelReadEventListener;
        }

        @Override
        public void invoke(T data, AnalysisContext context) {
            dataList.add(data);
            excelReadEventListener.onRow(data);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            excelReadEventListener.onAllRowReadComplete(dataList);
        }
    }


    public ExcelUtilReadHandlerForEasy(InputStream inputStream) {
        super(inputStream);
        excelReader = EasyExcel.read(inputStream).build();
    }

    @Override
    public <T> void readSheet(Integer sheetIndex, Class<T> readClazz, ExcelUtil.ExcelReadEventListener<T> excelReadEventListener) {
        ReadSheet sheet = EasyExcel.readSheet(sheetIndex).head(readClazz).registerReadListener(new ReadListenerImpl<>(excelReadEventListener)).build();
        excelReader.read(sheet);
    }

    @Override
    public <T> void readAllSheet(Class<T> readClazz, ExcelUtil.ExcelReadEventListener<T> excelReadEventListener) {
        try {
            for (ReadSheet sheet : excelReader.excelExecutor().sheetList()) {
                readSheet(sheet.getSheetNo(), readClazz, excelReadEventListener);
            }
        }finally {
            finish();
        }
    }

    @Override
    public void finish() {
        if (excelReader != null) {
            excelReader.finish();
        }
    }
}
